package com.ebuy.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.ebuy.factory.DBConnectionFactory;
import com.ebuy.model.ProductType;
import com.mysql.jdbc.PreparedStatement;

public class ProductTypeDAO {

	private static final String GET_ALL_PRODUCT_TYPE = "SELECT * FROM product_type";
	private static final String GET_SINGLE_PRODUCT_TYPE = "SELECT * FROM product_type WHERE id = ?";

	public ArrayList<ProductType> getAllProductType() {
		ArrayList<ProductType> arr = new ArrayList<ProductType>();
		Connection conn = DBConnectionFactory.getInstance().getConnection();

		try {
			PreparedStatement st = (PreparedStatement) conn
					.prepareStatement(GET_ALL_PRODUCT_TYPE);

			ResultSet rs = st.executeQuery();

			while (rs.next()) {
				ProductType p = new ProductType();

				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));

				arr.add(p);
			}

			if (st != null) {
				st.close();
			}

		} catch (Exception e) {

		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}

		if (arr.size() > 0) {
			return arr;
		} else {
			return null;
		}
	}

	public ProductType getSingleProductType(int id) {
		ProductType p = null;
		Connection conn = DBConnectionFactory.getInstance().getConnection();

		try {
			PreparedStatement st = (PreparedStatement) conn
					.prepareStatement(GET_SINGLE_PRODUCT_TYPE);

			st.setInt(1, id);

			ResultSet rs = st.executeQuery();

			if (rs.next()) {
				p = new ProductType();

				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));
			}

			if (st != null) {
				st.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}

		if (p != null) {
			return p;
		} else {
			return null;
		}

	}
}
